package com.andro.inje.chansung.bus;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.andro.inje.chansung.ConstantName;
import com.andro.inje.chansung.ConstantURL;
import com.andro.inje.chansung.DB;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class BusUpdateThread extends Thread {
	
	private Handler handler;
	private Activity activity;
	
	public BusUpdateThread(Activity activity, Handler handler) {
		this.activity = activity;
		this.handler  = handler;
	}
	
	public void run() {
		try {
			Document doc = Jsoup.connect(ConstantURL.BUS_BASIC_INFO_URL).get();
			Elements titles = doc.select("name");
			
			SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			for( Element element : titles ) {
				if( element.attr("title").contains("/") && !element.attr("title").contains("(") && !element.attr("title").contains(")")) {
					String[] buses = element.attr("title").split("/");
					
					for( int i = 0; i < buses.length; i++ ) {
						Bus bus = new Bus(buses[i],
						          element.select("ticket").get(0).text(),
						          element.select("card").get(0).text());
						DB.insertBasicDataIntoBusTable(db, bus);					
					}
				} else {
					String title = element.attr("title");
					if( title.contains("(") && title.contains(")") ) {
						title = title.substring(0, title.indexOf("("));
					}
					Bus bus = new Bus(title,
							          element.select("ticket").get(0).text(),
							          element.select("card").get(0).text());
					DB.insertBasicDataIntoBusTable(db, bus);
				}
			}
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
	}
}
